package com.hp.bon.sgw.wh.channel.handler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.core.BuzProcessorManager;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.channel.SoapChannel;
import com.hp.bon.sgw.core.channel.handler.IAsynCallHandler;
import com.hp.bon.sgw.start.SpringContext;
import com.hp.bon.sgw.threads.TaskManager;
import com.hp.bon.sgw.wh.bean.QueryRatableDetailResponse;
import com.hp.bon.sgw.wh.service.UserResourceConfigService;
import com.hp.bon.sgw.wh.utils.LogUtil;
import com.hp.bon.sgw.wh.utils.ResultCodeUtil;
import com.hp.ocs.diameter.message.Message;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import org.simpleframework.http.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AccuUseDetailQryHandle implements IAsynCallHandler {
    private static final Logger _log = LoggerFactory.getLogger(AccuUseDetailQryHandle.class);
    private PrintStream printStream;
    private UserResourceConfigService userResourceConfigService ;
    private long startTime;
    private Request request;
    private JSONObject jsonContent;
    public AccuUseDetailQryHandle(PrintStream printStream, Request request, long startTime, JSONObject jsonContent) {
        this.printStream = printStream;
        this.startTime = startTime;
        this.request = request;
        this.jsonContent=jsonContent;
    }

    @Override
    public int getProtocolType() {
        return 0;
    }

    @Override
    public void onCallResult(CallParam callParam) {
        _log.info("=================http AccuUseDetailQryHandle  onCallResult()" );
        XmlMessage ack = null;
        Object response = null;
        if (callParam.getResponse() != null) {
            response = callParam.getResponse();
        } else if (callParam.getRecvResponse() != null) {
            response = callParam.getRecvResponse();
        }
        if (response == null) {
            int _retcodeTmp = callParam.getRetCode() == 3002 ? 11202 : callParam.getRetCode();
            ack = SoapChannel.createERRAnwser(callParam.getSessionId(), _retcodeTmp, callParam.getResultMsg());
            callParam.setServiceResultCode(_retcodeTmp);// 11203
        } else {
            if (response instanceof Message) {// CCA -> XML
                ack = BuzProcessorManager.getInstance().convertMessageToAck(callParam);
            } else if (response instanceof XmlMessage) {
                ack = (XmlMessage) response;
            } else {
                _log.warn("unknown response type:" + callParam.getResponse().getClass().getName());
            }
        }
        try {
            String respXML="";
            try {
                respXML = convertResponseString(ack, callParam.getServiceResultCode());
            }catch (Exception e) {
                _log.info("=====respXML:Exception ",e);
            }

            byte[] resp = respXML.getBytes("UTF-8");
            ack.setLength(resp.length);
            ack.setMsgTime(System.currentTimeMillis());
            printStream.write(resp);
            printStream.close();
            callParam.setResponse(ack);
//			if (callParam.getRetCode() == Constants.ResultCode.SUCCESS) {// 成功的消息，请求应答入库
//				MessageDetail detail = new MessageDetail();
//				detail.setBusinessCallId(callParam.getBussinessCallId());
//				detail.setSessionId(callParam.getSessionId());
//				detail.setServiceContextId(callParam.getServiceContextId());
//				detail.setMessageType(MessageType.WSA);
//				detail.setDetails(ack.getDATA());
//				detail.setMsgTime(new Date(ack.getMsgTime()));
//				detail.setOpType("send");
//				detail.setHostId(callParam.getUserName());
//				MessageDetailCacheManager.getInstance().add(detail);
//			}
            //记录到日志
            LogUtil.saveLogToABM(request,respXML,startTime);
            TaskManager.taskProcess(callParam);
            _log.info("http response(returnBalance) " + respXML);

        } catch (UnsupportedEncodingException e) {
            _log.info("convertResponseString UnsupportedEncodingException error,msg=" + e.getMessage());
        } catch (IOException e) {
            _log.info("convertResponseString IOException,msg=" + e.getMessage());
        }
    }



    /**
     * 从Message中解析出需要的数据，并拼接成json字符串
     * @param answer
     * @param serviceResultCode
     * @return
     */
    private String convertResponseString(XmlMessage ack, int serviceResultCode) {
        _log.info("AccuUseDetailQryHandle serviceResultCode = {}", serviceResultCode);
        _log.info("===========service_result_code===============" + serviceResultCode);
        String response = "";
        Map<String, Object> data = new HashMap<String, Object>();
        if (serviceResultCode == 0) {
            response = ack.getDATA();
            userResourceConfigService = SpringContext.getApplicationContext().getBean(UserResourceConfigService.class);
            String jf3_ratable_flag=userResourceConfigService.getValue("jf3_ratable_flag", "0");
            _log.info("=====================jf3_ratable_flag=============="+jf3_ratable_flag);
            if(jf3_ratable_flag.equals("1")){
                _log.info("=====================进入新程序数据解析==============");
                //新流程
                try{
                    com.alibaba.fastjson.JSONObject responseJson= JSONObject.parseObject(response);
                    String resultCode=responseJson.getString("resultCode");
                    String resultMsg=responseJson.getString("resultMsg");
                    _log.info("===========service_result_code===============" + resultCode);
                    if("0".equals(resultCode)){
                        JSONArray  DetailOfferInstInfo=responseJson.getJSONArray("DetailOfferInstInfo");
                        if(DetailOfferInstInfo == null){
                            DetailOfferInstInfo=new JSONArray();
                        }else{
                            for (int i = 0; i < DetailOfferInstInfo.size(); i++) {
                                JSONObject jsonObject = DetailOfferInstInfo.getJSONObject(i);
                                JSONArray jsonArray = jsonObject.getJSONArray("AccuQryUserList");
                                for (int j = 0; j < jsonArray.size(); j++) {
                                    JSONObject jsonObject2 = jsonArray.getJSONObject(j);
                                    jsonObject2.put("carryFlag", Integer.valueOf(jsonObject2.getString("accuTypeId").substring(2,3)));
                                    jsonObject2.put("usageAmount", jsonObject2.getLong("usageAmount"));
                                    jsonObject2.put("accuTypeId", jsonObject2.getLong("accuTypeId"));
                                    jsonObject2.put("usageAmount", jsonObject2.getLong("usageAmount"));
                                }
                                jsonObject.put("accuQryUserList",jsonArray);
                                jsonObject.remove("AccuQryUserList");
                            }
                        }
                        data.put("detailOfferInstInfo", DetailOfferInstInfo);
                        data.put("resultCode","0");
                        data.put("resultMsg","SUCCESS");
                    }else{
                        data.put("resultCode", resultCode);
                        data.put("resultMsg", resultMsg);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    data.put("DetailOfferInstInfo","");
                    data.put("resultCode", "-1");
                    data.put("resultMsg", "查询失败");
                }
                String newCode = ResultCodeUtil.updateResultCode(data.get("resultCode"), userResourceConfigService.getValue("api_resultCode"), userResourceConfigService.getValue("api_defaultResult"));
                data.put("resultCode", newCode);
                return  new Gson().toJson(data);
            }
            _log.info("=====================进入老程序数据解析==============response="+response);
            response = response.substring(response.indexOf("<ServiceInformation>"), response.indexOf("</return>"));

            XStream xstream2 = new XStream(new DomDriver());
            xstream2.alias("ServiceInformation", QueryRatableDetailResponse.class);

            xstream2.alias("ProductOFFinfo", QueryRatableDetailResponse.ProductOFFinfo.class);

            xstream2.addImplicitCollection(QueryRatableDetailResponse.class, "ProductOFFinfos");//隐式集合 隐藏contentslist

            xstream2.alias("ServGroupQuery", QueryRatableDetailResponse.ProductOFFinfo.ServGroupQuery.class);

            xstream2.addImplicitCollection(QueryRatableDetailResponse.ProductOFFinfo.class, "ServGroupQuerys");//隐式集合 隐藏contentslist

            QueryRatableDetailResponse queryRatableDetailResponse = (QueryRatableDetailResponse) xstream2.fromXML(response);
            if(queryRatableDetailResponse==null) {
                data.put("DetailOfferInstInfo","");
                data.put("resultCode", "-1");
                data.put("resultMsg", "查询失败");
            }else if("0".equals(queryRatableDetailResponse.getServiceResultCode())){
                List<Map<String, Object>> DetailOfferInstInfos = new ArrayList<Map<String,Object>>();
                List<QueryRatableDetailResponse.ProductOFFinfo> productOFFinfos = queryRatableDetailResponse.getProductOFFinfos();

                if(!CollectionUtils.isEmpty(productOFFinfos)) {
                    for(QueryRatableDetailResponse.ProductOFFinfo productOFFinfo:productOFFinfos) {
                        Map<String, Object> DetailOfferInstInfo = new HashMap<String, Object>();
                        DetailOfferInstInfo.put("offerId",productOFFinfo.getProductOfferId());
                        DetailOfferInstInfo.put("offerInstId",productOFFinfo.getProdOfferInstanceId());
                        List<Map<String, Object>> AccuQryUserList = new ArrayList<Map<String,Object>>();
                        List<QueryRatableDetailResponse.ProductOFFinfo.ServGroupQuery> servGroupQueries = productOFFinfo.getServGroupQuerys();
                        if(!CollectionUtils.isEmpty(servGroupQueries)) {
                            for(QueryRatableDetailResponse.ProductOFFinfo.ServGroupQuery servGroupQuery:servGroupQueries) {
                                Map<String, Object> AccuQryUser = new HashMap<String, Object>();
                                AccuQryUser.put("accNbr",servGroupQuery.getAccNbr());
                                AccuQryUser.put("accuTypeId",toLong(servGroupQuery.getRatableResourceID()));
                                AccuQryUser.put("carryFlag",toLong(servGroupQuery.getRatableResourceID().substring(2, 3)));//结转标识
                                AccuQryUser.put("servTypeId",servGroupQuery.getServTypeId());//用户类型
                                AccuQryUser.put("destinationAttr",servGroupQuery.getDestinationAttr());//用户属性
                                AccuQryUser.put("usageAmount",toLong(servGroupQuery.getUsageAmount()));//使用量
                                AccuQryUser.put("unitTypeId",servGroupQuery.getUnitTypeId());//量本单位类型
                                AccuQryUserList.add(AccuQryUser);
                                _log.info("========carryFlag="+AccuQryUser.get("carryFlag"));
                            }
                        }

                        DetailOfferInstInfo.put("AccuQryUserList",AccuQryUserList);
                        DetailOfferInstInfos.add(DetailOfferInstInfo);
                    }
                }

                data.put("DetailOfferInstInfo", DetailOfferInstInfos);
                data.put("resultCode","0");
                data.put("resultMsg","SUCCESS");
            }else{
                data.put("resultCode", queryRatableDetailResponse.getServiceResultCode());
                data.put("resultMsg", queryRatableDetailResponse.getParaFieldResult());
            }
            _log.info("AccuUseDetailQryHandle convertResponseString = {}", response);
        }else {
            data.put("resultCode", "-1");
            data.put("resultMsg", "查询失败");
        }
        String newCode = ResultCodeUtil.updateResultCode(data.get("resultCode"), userResourceConfigService.getValue("api_resultCode"), userResourceConfigService.getValue("api_defaultResult"));
        data.put("resultCode", newCode);
        Gson gson = new Gson();
        response = gson.toJson(data);
        return response;
    }

    private Long toLong(String str) {
        try {
            return Long.valueOf(str);
        } catch (Exception e) {
            return 0l;
        }
    }

}
